package util;

import javax.swing.*;
import javax.swing.text.*;

import textfileproces.FileConversion;
import textfileproces.arff.CSV2ARFF;

import java.awt.*;
import java.io.*;
import java.net.URL;
import java.awt.event.*;
import java.util.Hashtable;

public class TextEditor extends JFrame {

    private static final String RESOURCE_ICONS_PATH = "icons/";

    private URL iconOpen = getClass ().getClassLoader ().getResource (RESOURCE_ICONS_PATH + "open.gif");
    private URL iconCut = getClass ().getClassLoader ().getResource (RESOURCE_ICONS_PATH + "cut.gif");
    private URL iconCopy = getClass ().getClassLoader ().getResource (RESOURCE_ICONS_PATH + "copy.gif");
    private URL iconPaste = getClass ().getClassLoader ().getResource (RESOURCE_ICONS_PATH + "paste.gif");
    private URL iconSave= getClass ().getClassLoader ().getResource (RESOURCE_ICONS_PATH + "save.gif");
    private ImageIcon imageOpen = new ImageIcon(iconOpen);
    private ImageIcon imageSave = new ImageIcon(iconSave);

	private Action openAction = new OpenAction();
	private Action saveAction = new SaveAction();

	private JTextComponent textComp;
	private Hashtable actionHash = new Hashtable();
	private BufferedReader reader;
	private BufferedWriter writer;

	public static void main(String[] args) throws IOException {
		FileConversion conversion = new CSV2ARFF(args[0], args[1]);
		conversion.createReaderAndWriter();
		TextEditor editor = new TextEditor(conversion.getReader(), conversion.getWriter());
		editor.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		editor.setVisible(true);
	}

	// Create an editor.
	public TextEditor(BufferedReader reader, BufferedWriter writer) throws IOException {
		super("Simple Editor");
		this.reader = reader;
		this.writer = writer;
		centerWindow();
		textComp = createTextComponent();
		makeActionsPretty();

		Container content = getContentPane();
		content.add(textComp, BorderLayout.CENTER);
		content.add(createToolBar(), BorderLayout.NORTH);
		setJMenuBar(createMenuBar());
		setSize(320, 240);
		readText(reader);
	}

	private void readText(BufferedReader reader) throws IOException {
		if (reader != null) {
			String line = null;
			while ((line = reader.readLine()) != null)  {
				((JTextArea) textComp).append(line + "\n");
			}
		}
	}

	protected JTextComponent createTextComponent() {
		JTextArea textArea = new JTextArea();
		textArea.setLineWrap(true);
		return textArea;
	}

	// Add icons and friendly names to actions we care about.
	protected void makeActionsPretty() {
		Action a;

		a = textComp.getActionMap().get(DefaultEditorKit.cutAction);
		a.putValue(Action.SMALL_ICON, new ImageIcon(iconCut));
		a.putValue(Action.NAME, "Cut");

		a = textComp.getActionMap().get(DefaultEditorKit.copyAction);
		a.putValue(Action.SMALL_ICON, new ImageIcon(iconCopy));
		a.putValue(Action.NAME, "Copy");

		a = textComp.getActionMap().get(DefaultEditorKit.pasteAction);
		a.putValue(Action.SMALL_ICON, new ImageIcon(iconPaste));
		a.putValue(Action.NAME, "Paste");

		a = textComp.getActionMap().get(DefaultEditorKit.selectAllAction);
		a.putValue(Action.NAME, "Select All");
	}

	// Create a simple JToolBar with some buttons.
	protected JToolBar createToolBar() {
		JToolBar bar = new JToolBar();

		// Add simple actions for opening & saving.
		bar.add(getOpenAction()).setText("");
		bar.add(getSaveAction()).setText("");
		bar.addSeparator();

		// Add cut/copy/paste buttons.
		bar.add(textComp.getActionMap().get(DefaultEditorKit.cutAction)).setText("");
		bar.add(textComp.getActionMap().get(
				DefaultEditorKit.copyAction)).setText("");
		bar.add(textComp.getActionMap().get(
				DefaultEditorKit.pasteAction)).setText("");
		return bar;
	}

	// Create a JMenuBar with file & edit menus.
	protected JMenuBar createMenuBar() {
		JMenuBar menubar = new JMenuBar();
		JMenu file = new JMenu("File");
		JMenu edit = new JMenu("Edit");
		menubar.add(file);
		menubar.add(edit);

		file.add(getOpenAction());
		file.add(getSaveAction());
		file.add(new ExitAction());
		edit.add(textComp.getActionMap().get(DefaultEditorKit.cutAction));
		edit.add(textComp.getActionMap().get(DefaultEditorKit.copyAction));
		edit.add(textComp.getActionMap().get(DefaultEditorKit.pasteAction));
		edit.add(textComp.getActionMap().get(DefaultEditorKit.selectAllAction));
		return menubar;
	}

	// Subclass can override to use a different open action.
	protected Action getOpenAction() { return openAction; }

	// Subclass can override to use a different save action.
	protected Action getSaveAction() { return saveAction; }

	protected JTextComponent getTextComponent() { return textComp; }

	// ********** ACTION INNER CLASSES ********** //

	// A very simple exit action
	public class ExitAction extends AbstractAction {
		public ExitAction() { super("Exit"); }
		public void actionPerformed(ActionEvent ev) { 
			System.exit(0); 
		}
	}

	// An action that opens an existing file
	class OpenAction extends AbstractAction {
		public OpenAction() { 
			super("Open", imageOpen); 
		}

		// Query user for a filename and attempt to open and read the file into the
		// text component.
		public void actionPerformed(ActionEvent ev) {
			JFileChooser chooser = new JFileChooser();
			if (chooser.showOpenDialog(TextEditor.this) !=
					JFileChooser.APPROVE_OPTION)
				return;
			File file = chooser.getSelectedFile();
			if (file == null)
				return;

			FileReader reader = null;
			try {
				reader = new FileReader(file);
				textComp.read(reader, null);
			}
			catch (IOException ex) {
				JOptionPane.showMessageDialog(TextEditor.this,
						"File Not Found", "ERROR", JOptionPane.ERROR_MESSAGE);
			}
			finally {
				if (reader != null) {
					try {
						reader.close();
					} catch (IOException x) {}
				}
			}
		}
	}

	// An action that saves the document to a file
	class SaveAction extends AbstractAction {
		public SaveAction() {
			super("Save", imageSave);
		}

		// Query user for a filename and attempt to open and write the text
		// component’s content to the file.
		public void actionPerformed(ActionEvent ev) {
			JFileChooser chooser = new JFileChooser();
			if (chooser.showSaveDialog(TextEditor.this) !=
					JFileChooser.APPROVE_OPTION)
				return;
			File file = chooser.getSelectedFile();
			if (file == null)
				return;

			FileWriter writer = null;
			try {
				writer = new FileWriter(file);
				textComp.write(writer);
			}
			catch (IOException ex) {
				JOptionPane.showMessageDialog(TextEditor.this,
						"File Not Saved", "ERROR", JOptionPane.ERROR_MESSAGE);
			}
			finally {
				if (writer != null) {
					try {
						writer.close();
					} catch (IOException x) {}
				}
			}
		}
	}

	public void centerWindow() {
	    Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();
	    int x = (int) ((dimension.getWidth() - this.getWidth()) / 2);
	    int y = (int) ((dimension.getHeight() - this.getHeight()) / 2);
		this.setLocation(x, y);
	}
}

